package com.songlanyun.common.kqUtils;

import java.math.BigDecimal;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class InitQuery{
	public static Log logger = LogFactory.getLog(InitOrder.class);

	public static QuickPayProperties quickPayProperties;
	private static final String appScheme = "billdemo";   //支付宝支付填写参数
	private static final String appName = "惠选中亿";   //APP名称

	@Autowired
	public InitQuery(QuickPayProperties properties) {
		quickPayProperties = properties;
	}

	public static void main(String[] args) {
		gateWayInitQuery();
	}

	/**
	 * 快钱订单查询
	 */
	public static Map<String, Object> gateWayInitQuery(String orderCode) {
		Map<String, Object> request = new HashMap<String, Object>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		//会员编号
		request.put("memberCode", quickPayProperties.getMemberCode());
		//商户编号
		request.put("merchantId", quickPayProperties.getMerchantId());
		//商户对应的终端编号
		request.put("terminalId", quickPayProperties.getTerminalCode());
		//交易类型:RFD
		request.put("txnType", "QRY");
		request.put("origTxnType", "ODR");
		//商户订单号
		request.put("externalTraceNo", orderCode);

		Sign sign = new Sign();
		sign.init(quickPayProperties);
		sign.createPrivateKey();
		String s = sign.doSign(request);
		request.put("sign", s);
		sign.createPublicKey();

		// 输出请求报文的内容
		logger.info("查询报文的请求参数:" + JSON.toJSONString(request));
		//测试环境下提交地址
		//String reqUrl = "https://sandbox.99bill.com/sdk-gateway/sdkGatewayService";
		//生产环境下提交地址
		String reqUrl = "https://picsdk.99bill.com/sdk-gateway/sdkGatewayService";

		String response = "";
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			response = HttpUtil.doPostJsonRequestByHttps(JSON.toJSONString(request), reqUrl, 3000, 80000);
			resultMap = JSON.parseObject(response, Map.class);
			logger.info("快钱返回的JSON对象===" + resultMap);
			logger.info("快钱返回的Response对象===" + response);
			sign.verificate(String.valueOf(resultMap.get("sign")), resultMap);
			return resultMap;
		} catch (Exception e) {
			logger.error("快钱查询异常：\n" + e.getStackTrace() + "\nInitReFund.java\n" + e.getMessage());
			resultMap.put("error", e);
			return resultMap;
		}
	}
	
	/**
	 * gateWay查询demo
	 */
	public static void gateWayInitQuery()
	{
		Map<String, Object> request = new HashMap<String, Object>();
;
		String externalTraceNo = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()) + "ts";
		//会员编号
		request.put("memberCode", "10012155863");
		//商户编号
		request.put("merchantId", "812331545110013");
		//商户对应的终端编号
		request.put("terminalId", "33150025");
		//交易类型:QRY
		request.put("txnType", "QRY");//QRY QSP
		//快钱交易控制编号
		//request.put("idBizCtrl", "15074374981");
		//商户订单号
		request.put("externalTraceNo", "JH20210716064521");//2019071106281524014_82424
        //交易类型(ODR或RFD)
		request.put("origTxnType", "ODR");
		Sign sign = new Sign();
		sign.createPrivateKey();
		String s = sign.doSign(request);
		request.put("sign", s);
		sign.createPublicKey();
		System.out.println("请求参数:" + JSON.toJSONString(request));
		
		//sandbox提交地址
//		String reqUrl = "https://sandbox.99bill.com/sdk-gateway/sdkGatewayService";
		String reqUrl = "https://picsdk.99bill.com/sdk-gateway/sdkGatewayService";

		
		String response = "";
		
		try {

			response = HttpUtil.doPostJsonRequestByHttps(JSON.toJSONString(request), reqUrl, 3000, 8000);

			Map<String,Object> m = new HashMap<String, Object>();
			m = JSON.parseObject(response, Map.class);
			System.out.println("m==="+m);
			System.out.println("response==="+response);
			sign.verificate(m.get("sign").toString(), m);
			
			
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
	}
	/**
	 * HTTP请求POST方式
	 * 
	 * @param requestObject
	 * @param url
	 * @param connectTimeout
	 * @param socketTimeOut
	 * @return
	 * @throws Exception
	 */
	public static String postHttpRequest(Object requestObject, String url, int connectTimeout, int socketTimeOut)
			throws Exception {
		CloseableHttpResponse response = null;
		try {
			String reqeustString = "{}";
			if (requestObject != null) {
				reqeustString = JSON.toJSONString(requestObject);
			}
			logger.info("[send to gateWay service] message : " + reqeustString);
			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			StringEntity sEntity = new StringEntity(reqeustString, "UTF-8");
			sEntity.setContentType("application/json");
			// 
			RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectTimeout)
					.setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeOut).build();
			httpPost.setConfig(requestConfig);
			httpPost.setEntity(sEntity);
			response = httpclient.execute(httpPost);
			// get http status code
			int resStatu = response.getStatusLine().getStatusCode();
			String responseString = null;
			if (resStatu == HttpStatus.SC_OK) {
				responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
			} else {
				logger.error("rquestUrl:" + url + ", the connection is error,statusCode=" + resStatu);
				throw new Exception(url + ",the statusCode is " + resStatu);
			}
			return responseString;
		} catch (ConnectTimeoutException e) {
			logger.error("http post connection timeout", e);
			throw e;
		} catch (SocketTimeoutException e) {
			logger.error("http post socket timeout", e);
			throw e;
		} catch (Exception e) {
			logger.error("http post throw Exception", e);
			throw e;
		} finally {
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
					response.close();
				} catch (Exception e) {
					logger.error("http connection closed error", e);
				}
			}
		}
	}
	
}
